<template>
   <div>
     <el-upload 
        list-type="picture-card"
        :file-list="fileList"
        :on-remove="onRemove"
        :on-preview="onPreview"
        :on-change="onChange"
        :before-upload="beforeUpload"
        action="#"
        :class="{ hidden:fileComputed }"
        :http-request="httpRequest"
      >
        <i class="el-icon-plus" />
        <el-progress  v-if="percentageShow" :percentage="percentage"></el-progress>
      </el-upload>
      <el-dialog  title="预览图片" :visible.sync="showDialog" width="30%">
        <img style="width:100%" :src="imgUrl" alt="">
      </el-dialog>
   </div>
</template>

<script>

export default {
  name:'ImageUpload',
  data() {
    return {
      // 图片地址设置为数组 
      fileList: [
        // {name:'test.jpg',url:'http://yun.itheima.com/Upload/Images/20220401/6246adf58fb35.jpg'},
      ], 
      showDialog: false, // 控制显示弹层
      imgUrl: '', // 预览图片地址
      currentFileUid:'',  // 当前上传的uid
      percentage:0, // 进度条
      percentageShow:false // 进度条显示
    }
  },
  computed: {
    fileComputed(){
      return this.fileList.length === 2
    }
  },
  methods: {
    // 移除事件
    onRemove(val) {
      this.fileList = this.fileList.filter(item=>item.uid !== val.uid)
    },
    // 预览事件
    onPreview({ url }){
      this.imgUrl = url
      this.showDialog = true
    },
    onChange(file, fileList){
      this.fileList = fileList.map(item=>item)
    },
    // 上传前的操作
    beforeUpload(file){
      // 体积检测
      const maxSize = 7  // 最大5M
      if((file.size / 1024 / 1024) > maxSize){
        this.$message.warning(`体积不能超过${maxSize}M`)
        return false
      }
      // 类型检测
      const types = ['image/png','image/jpg','image/jpeg','image/gif']
      if(!types.includes(file.type)){
        this.$message.warning('文件支支持jpg,png,gif,jpeg')
        return Promise.reject('类型错误')
      }
      // 记录这一次上传的uid
      this.currentFileUid = file.uid
      // 进度条打开
      this.percentageShow = true
    },
    // 上传行为
    httpRequest(file){
     
    }
  },
}
</script>
<style lang="scss" scoped>
// less   /deep/
// scss   ::v-deep
.hidden {
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}
</style>